﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BullTasDesaDal.Service;
using BullTasDesaDal.Entities;
using System.Globalization;
using System.Web.UI.DataVisualization.Charting;

namespace WSBulTasDesa
{
    public partial class wfLandAnalysis : System.Web.UI.Page
    {
        private Analysis analysis
        {
            get
            {
                if (Session["analysis"] != null)
                    return (Session["analysis"] as Analysis);
                else
                {
                    analysis = new Analysis();
                    return analysis;
                }
            }
            set
            {
                Session["analysis"] = value;
            }
        }

        private Dictionary<string, decimal> lLandChart
        {
            get
            {
                if (Session["landChart"] != null)
                    return (Session["landChart"] as Dictionary<string, decimal>);
                else
                {
                    lLandChart = new Dictionary<string, decimal>();
                    return lLandChart;

                }
            }
            set
            {
                Session["landChart"] = value;
            }
        }



        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {


                if (!string.IsNullOrEmpty(Request.QueryString["idAppraisal"]))
                {
                    Analysis auxAnalysis = AnalysisService.GetLastAnalysis(int.Parse(Request.QueryString["idAppraisal"]));
                    if (auxAnalysis != null)
                    {
                        analysis = auxAnalysis;
                    }
                    else
                    {
                        analysis.Appraisal.Id = int.Parse(Request.QueryString["idAppraisal"]);
                        analysis.Version = 0;
                    }
                }
                else if (!string.IsNullOrEmpty(Request.QueryString["idAnalysis"]))
                {
                    analysis = AnalysisService.GetById(Int64.Parse(Request.QueryString["idAnalysis"]));
                }


                LoadGridLand();
                LoadGridBetCamp();
                LoadGridBetBody();
                Calculate();


            }
            BindCharBettLand();
            BindCharLandClasification();
        }

        protected void LoadGridLand()
        {
            IList<LandCategory> llandCategory = AnalysisService.GetAllLandCategorys();
            if (analysis.Lands.Count > 0)
            {

                foreach (LandCategory landCategory in llandCategory)
                {
                    foreach (LandClasification landClasification in landCategory.LandClasification)
                    {

                        landClasification.Land = analysis.Lands.Where(x => x.LandClasification.Id == landClasification.Id).Single();

                    }
                }

            }
            grvLandCategory.DataSource = llandCategory;
            grvLandCategory.DataBind();


        }

        protected void LoadGridBetCamp()
        {
            grvBetCamp.DataSource = analysis.Betterments.Where(x => x.Type == "C").ToList();
            grvBetCamp.DataBind();
        }

        protected void LoadGridBetBody()
        {
            grvBetBody.DataSource = analysis.Betterments.Where(x => x.Type == "B").ToList();
            grvBetBody.DataBind();
        }

        protected void Calculate()
        {
            //Land
            //Ha superficie
            decimal ha = 0;
            decimal subTotalHa = 0;
            //Total Item
            decimal subTotalItem = 0;
            decimal totalItem = 0;
            lLandChart.Clear();

            foreach (GridViewRow gParentRow in grvLandCategory.Rows)
            {
                if (gParentRow.RowType == DataControlRowType.DataRow)
                {
                    Label lblLandCategoryName = gParentRow.FindControl("lblLandCategoryName") as Label;
                    GridView gv = gParentRow.FindControl("grvLandClasification") as GridView;
                    GridViewRow footerChildRow = gv.FooterRow;

                    foreach (GridViewRow gChildRow in gv.Rows)
                    {
                        //Area
                        Label lblSubTotalArea = footerChildRow.FindControl("lblSubTotalHa") as Label;
                        ha = Convert.ToDecimal((gChildRow.FindControl("txtHa") as TextBox).Text, CultureInfo.InvariantCulture.NumberFormat);
                        subTotalHa += ha;
                        lblSubTotalArea.Text = subTotalHa.ToString();
                        //Total Item
                        Label lblTotal = footerChildRow.FindControl("lblTotalItem") as Label;
                        int priceHa = int.Parse((gChildRow.FindControl("txtPriceHa") as TextBox).Text);
                        subTotalItem = ha * priceHa;
                        totalItem += subTotalItem;
                        (gChildRow.FindControl("lblSubTotalItem") as Label).Text = string.Format("{0:c}", subTotalItem);
                        lblTotal.Text = string.Format("{0:c}", totalItem);


                        //Land


                        if (analysis.Lands.Where(x => x.LandClasification.Id == gv.DataKeys[gChildRow.RowIndex].Value.ToString()).SingleOrDefault() != null)
                        {
                            analysis.Lands.Where(x => x.LandClasification.Id == gv.DataKeys[gChildRow.RowIndex].Value.ToString()).Single().Ha = ha;
                            analysis.Lands.Where(x => x.LandClasification.Id == gv.DataKeys[gChildRow.RowIndex].Value.ToString()).Single().PriceHa = priceHa;
                        }
                        else
                        {

                            Land land = new Land();
                            LandClasification landClasification = new LandClasification();
                            landClasification.Id = gv.DataKeys[gChildRow.RowIndex].Value.ToString();
                            landClasification.Color = (gChildRow.FindControl("txtHa") as TextBox).BackColor.Name.ToString();
                            if (analysis.Lands.Count > 0)
                                land.Id = analysis.Lands.Max(x => x.Id) + 1;
                            else
                                land.Id = 0;
                            land.Ha = ha;
                            land.PriceHa = priceHa;
                            land.LandClasification = landClasification;
                            land.Analysis = analysis;
                            analysis.Lands.Add(land);
                        }




                    }

                    if (subTotalHa != 0)
                        lLandChart.Add(lblLandCategoryName.Text, subTotalHa);

                    subTotalHa = 0;
                    totalItem = 0;
                }


            }
            this.SetPercent();
            this.ShowTotals();



        }

        protected void btnCalculate_Click(object sender, EventArgs e)
        {
            this.Calculate();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Betterment betterment = new Betterment();

            TextBox txtName = grvBetCamp.HeaderRow.FindControl("txtName") as TextBox;
            DropDownList ddlMeasureUnit = grvBetCamp.HeaderRow.FindControl("ddlMeasureUnit") as DropDownList;
            TextBox txtQuantity = grvBetCamp.HeaderRow.FindControl("txtQuantity") as TextBox;
            TextBox txtValue = grvBetCamp.HeaderRow.FindControl("txtValue") as TextBox;

            if (analysis.Betterments.Count > 0)
                betterment.Id = analysis.Betterments.Max(x => x.Id) + 1;
            else
                betterment.Id = 0;
            betterment.Name = txtName.Text;
            betterment.MeasureUnit = ddlMeasureUnit.SelectedValue;
            betterment.Quantity = Convert.ToDecimal(txtQuantity.Text, CultureInfo.InvariantCulture.NumberFormat);
            betterment.Value = int.Parse(txtValue.Text);
            betterment.Type = "C";
            betterment.Analysis = analysis;
            analysis.Betterments.Add(betterment);

            txtName.Text = string.Empty;
            ddlMeasureUnit.SelectedValue = string.Empty;
            txtQuantity.Text = string.Empty;
            txtValue.Text = string.Empty;


            LoadGridBetCamp();

        }

        protected void btnAddBody_Click(object sender, EventArgs e)
        {
            Betterment betterment = new Betterment();

            TextBox txtName = grvBetBody.HeaderRow.FindControl("txtName") as TextBox;
            DropDownList ddlMeasureUnit = grvBetBody.HeaderRow.FindControl("ddlMeasureUnit") as DropDownList;
            TextBox txtQuantity = grvBetBody.HeaderRow.FindControl("txtQuantity") as TextBox;
            TextBox txtValue = grvBetBody.HeaderRow.FindControl("txtValue") as TextBox;

            if (analysis.Betterments.Count > 0)
                betterment.Id = analysis.Betterments.Max(x => x.Id) + 1;
            else
                betterment.Id = 0;
            betterment.Name = txtName.Text;
            betterment.MeasureUnit = ddlMeasureUnit.SelectedValue;
            betterment.Quantity = Convert.ToDecimal(txtQuantity.Text, CultureInfo.InvariantCulture.NumberFormat);
            betterment.Value = int.Parse(txtValue.Text);
            betterment.Type = "B";
            betterment.Analysis = analysis;
            analysis.Betterments.Add(betterment);

            txtName.Text = string.Empty;
            ddlMeasureUnit.SelectedValue = string.Empty;
            txtQuantity.Text = string.Empty;
            txtValue.Text = string.Empty;


            LoadGridBetBody();

        }



        protected void RemoveBet(Int64 index)
        {
            analysis.Betterments.Remove(analysis.Betterments.Where(x => x.Id == index).Single());
        }

        protected void UpdateBet(Int64 index, Betterment bet)
        {

            analysis.Betterments.Where(x => x.Id == index).Single().Name = bet.Name;
            analysis.Betterments.Where(x => x.Id == index).Single().MeasureUnit = bet.MeasureUnit;
            analysis.Betterments.Where(x => x.Id == index).Single().Quantity = bet.Quantity;
            analysis.Betterments.Where(x => x.Id == index).Single().Value = bet.Value;

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Analysis lastAnalysis = AnalysisService.GetLastAnalysis(analysis.Appraisal.Id);
            if (lastAnalysis == null)
                analysis.Version = 1;
            else
                analysis.Version = Convert.ToInt16(lastAnalysis.Version + 1);
            AnalysisService.Save(analysis);

            Response.Redirect("wfAppraisalList.aspx");
        }

        protected void SetPercent()
        {
            decimal granTotalHa = analysis.Lands.Sum(x => x.Ha);
            decimal ha = 0;

            foreach (GridViewRow gParentRow in grvLandCategory.Rows)
            {
                if (gParentRow.RowType == DataControlRowType.DataRow)
                {
                    GridView gv = gParentRow.FindControl("grvLandClasification") as GridView;
                    GridViewRow footerChildRow = gv.FooterRow;


                    //Porcent
                    foreach (GridViewRow gChildRow in gv.Rows)
                    {
                        ha = analysis.Lands.Where(x => x.LandClasification.Id == gv.DataKeys[gChildRow.RowIndex].Value.ToString()).Single().Ha;
                        TextBox txtPercent = gChildRow.FindControl("txtPercent") as TextBox;
                        if (granTotalHa != 0)
                            txtPercent.Text = String.Format("{0:p}", ha / granTotalHa);
                        else
                            txtPercent.Text = "0,00%";
                    }


                }


            }

        }

        protected void ShowTotals()
        {
            decimal granTotalBetterment = analysis.Betterments.Sum(x => x.Total);
            decimal granTotalLand = analysis.Lands.Sum(x => x.Total);
            decimal granTotalLandHa = analysis.Lands.Sum(x => x.Ha);

            lblTotalLand.Text = string.Format("{0:c}", granTotalLand);
            lblTotalBetterment.Text = string.Format("{0:c}", granTotalBetterment);

            if (granTotalLandHa != 0)
            {
                lblAverageLand.Text = string.Format("{0:c}", granTotalLand / granTotalLandHa);
                lblAverageBetterment.Text = string.Format("{0:c}", granTotalBetterment / granTotalLandHa);
            }
            else
            {
                lblAverageLand.Text = string.Format("{0:c}", 0);
                lblAverageBetterment.Text = string.Format("{0:c}", 0);
            }

            lblGrandTotal.Text = string.Format("{0:c}", granTotalLand + granTotalBetterment);

           

        }

        protected decimal GetTotalBet(string type)
        {
            return analysis.Betterments.Where(x => x.Type == type).Sum(x => x.Total);
        }


        protected void grvBetBody_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grvBetBody.EditIndex = -1;
            LoadGridBetBody();
        }

        protected void grvBetBody_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            Int64 index = Convert.ToInt64(grvBetBody.DataKeys[e.RowIndex].Value);
            RemoveBet(index);
            LoadGridBetBody();
        }

        protected void grvBetBody_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grvBetBody.EditIndex = e.NewEditIndex;
            LoadGridBetBody();
        }

        protected void grvBetBody_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Int64 index = Convert.ToInt64(grvBetBody.DataKeys[e.RowIndex].Value);
            Betterment bet = new Betterment();
            bet.Name = (grvBetBody.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text;
            bet.MeasureUnit = (grvBetBody.Rows[e.RowIndex].FindControl("ddlMeasureUnit") as DropDownList).SelectedValue;
            bet.Quantity = Convert.ToDecimal(((grvBetBody.Rows[e.RowIndex].FindControl("txtQuantity") as TextBox).Text), CultureInfo.InvariantCulture.NumberFormat);
            bet.Value = int.Parse((grvBetBody.Rows[e.RowIndex].FindControl("txtValue") as TextBox).Text);
            UpdateBet(index, bet);
            grvBetBody.EditIndex = -1;
            LoadGridBetBody();
        }



        protected void grvBetCamp_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grvBetCamp.EditIndex = e.NewEditIndex;
            LoadGridBetCamp();

        }

        protected void grvBetCamp_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grvBetCamp.EditIndex = -1;
            LoadGridBetCamp();
        }

        protected void grvBetCamp_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Int64 index = Convert.ToInt64(grvBetCamp.DataKeys[e.RowIndex].Value);
            Betterment bet = new Betterment();
            bet.Name = (grvBetCamp.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text;
            bet.MeasureUnit = (grvBetCamp.Rows[e.RowIndex].FindControl("ddlMeasureUnit") as DropDownList).SelectedValue;
            bet.Quantity = Convert.ToDecimal(((grvBetCamp.Rows[e.RowIndex].FindControl("txtQuantity") as TextBox).Text), CultureInfo.InvariantCulture.NumberFormat);
            bet.Value = int.Parse((grvBetCamp.Rows[e.RowIndex].FindControl("txtValue") as TextBox).Text);
            UpdateBet(index, bet);
            grvBetCamp.EditIndex = -1;
            LoadGridBetCamp();

        }

        protected void grvBetCamp_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            Int64 index = Convert.ToInt64(grvBetCamp.DataKeys[e.RowIndex].Value);
            RemoveBet(index);
            LoadGridBetCamp();
        }


        private void BindCharLandClasification()
        {
            chtLandClasification.Series[0]["PieLabelStyle"] = "Outside";
            chtLandClasification.Series[0].BorderWidth = 1;
            chtLandClasification.Series[0].BorderColor = System.Drawing.Color.FromArgb(26, 59, 105);

            chtLandClasification.Legends.Add("Legend1");
            chtLandClasification.Legends[0].Enabled = true;
            chtLandClasification.Legends[0].Docking = Docking.Bottom;
            chtLandClasification.Legends[0].Alignment = System.Drawing.StringAlignment.Center;

            chtLandClasification.Series[0].LegendText = "#PERCENT{P2}";

            chtLandClasification.DataManipulator.Sort(PointSortOrder.Descending, chtLandClasification.Series[0]);


            foreach (KeyValuePair<string, decimal> item in lLandChart)
            {
                chtLandClasification.Series[0].Points.AddXY(item.Key, item.Value);
            }
        }


        private void BindCharBettLand()
        {
            chtLandBett.Series[0]["PieLabelStyle"] = "Outside";
            chtLandBett.Series[0].BorderWidth = 1;
            chtLandBett.Series[0].BorderColor = System.Drawing.Color.FromArgb(26, 59, 105);
           
            chtLandBett.Legends.Add("Legend1");
            chtLandBett.Legends[0].Enabled = true;
            chtLandBett.Legends[0].Docking = Docking.Bottom;
            chtLandBett.Legends[0].Alignment = System.Drawing.StringAlignment.Center;
           
            chtLandBett.Series[0].LegendText = "#PERCENT{P2}";
            
            chtLandBett.DataManipulator.Sort(PointSortOrder.Descending, chtLandClasification.Series[0]);


            decimal granTotalBetterment = analysis.Betterments.Sum(x => x.Total);
            decimal granTotalLand = analysis.Lands.Sum(x => x.Total);
            //chart
            // Populate series data
            decimal[] yValues = { granTotalBetterment, granTotalLand };
            string[] xValues = { "Mejoras", "Suelo" };
            chtLandBett.Series["Default"].Points.DataBindXY(xValues, yValues);
     
        }


    }
}